<template></template>
<script>
import mqtt from 'mqtt';
import Speech from 'speak-tts'; // es6
import request from '@/utils/request';

export default {
    data() {
        return {
            message: '',
            //mqtt
            // connection: {
            //   host: '81.68.197.219',
            //   port: 8083,
            //   endpoint: '/mqtt',
            //   clean: true, // 保留会话
            //   connectTimeout: 4000, // 超时时间
            //   reconnectPeriod: 4000, // 重连时间间隔
            //   // 认证信息 this.guid()
            //   clientId: this.$route.query.deviceImei+"&WebTopo&"+new Date().getTime(),
            //   username: 'emqx',
            //   password: 'public',
            // },
            connection: {
                // host: '106.15.46.144',
                // port: 80,
                // endpoint: '/mqtt',
                clean: true, // 保留会话
                connectTimeout: 4000, // 超时时间
                reconnectPeriod: 4000, // 重连时间间隔
                // 认证信息 this.guid()
                // clientId: this.$route.query.deviceImei+"&WebTopo&"+new Date().getTime(),
                clientId: 'server-' + new Date().getTime(),
                username: 'yanfan',
                password: 'yanfan',
            },
            subscription: [],
            receiveNews: '',
            client: {
                connected: false,
            },
            subscribeSuccess: false,
            bindList: [],
            speech: null,
            pageToken: '',
        };
    },
    components: {},
    created() {
        this.createConnection();
    },
    mounted() {
        if (this.$route.query.accessToken) {
            this.pageToken = this.$route.query.accessToken;
        }
        this.speechInit();
    },
    beforeDestroy() {
        this.destroyConnection();
        this.speech.cancel();
    },
    methods: {
        speechInit() {
            this.speech = new Speech();
            //设置语言
            this.speech.setLanguage('zh-CN');
            //设置速率 设置说话的速度(0.1-10 默认1，值越大语速越快,越小语速越慢)
            this.speech.setRate(1);
            //设置音量 设置说话的音量
            this.speech.setVolume(0);
            // 设置话语的音调(0-2 默认1，值越大越尖锐,越低越低沉)
            this.speech.setPitch('2');
            this.speech.init().then(() => {
                console.log('声音组件初始化完成');
            });
        },
        //播放按钮
        play(text) {
            this.speech
                .speak({
                    text: text,
                    listeners: {
                        //开始播放
                        onstart: () => {
                            console.log('Start utterance');
                        },
                        //判断播放是否完毕
                        onend: () => {
                            console.log('End utterance');
                        },
                        //恢复播放
                        onresume: () => {
                            console.log('Resume utterance');
                        },
                    },
                })
                .then(() => {
                    console.log('读取成功');
                });
        },
        getBindList() {
            let url = '/zutai/bDeviceZtBind/list';
            let param = {
                ztGuid: this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid,
            };
            request({
                url: url,
                method: 'get',
                headers: {
                    Authorization: 'Bearer ' + this.pageToken,
                },
                params: param,
            })
                .then((res) => {
                    // console.log("设备绑定",res.rows);
                    res.rows.forEach((element) => {
                        let data = {
                            deviceMac: element.deviceMac,
                        };
                        this.bindList.push(data);
                    });
                    //开始订阅
                    try {
                        this.doSubscribe();
                    } catch (error) {
                        // console.log("设备订阅失败",error);
                    }
                    try {
                        this.mqttPublish();
                    } catch (error) {
                        // console.log("设备预览失败",error);
                    }
                })
                .catch((error) => {
                    // console.log("获取设备绑定失败",error)
                });
        },
        S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        },
        guid() {
            return this.$store.state.app.guid ? this.$store.state.app.guid : this.$route.query.guid + '&' + new Date().getTime();
        },
        // 创建连接
        createConnection() {
            console.log('mqtt开始连接');
            // 连接字符串, 通过协议指定使用的连接方式
            // ws 未加密 WebSocket 连接
            // wss 加密 WebSocket 连接
            // mqtt 未加密 TCP 连接
            // mqtts 加密 TCP 连接
            // wxs 微信小程序连接
            // alis 支付宝小程序连接
            //this.destroyConnection();
            const { ...options } = this.connection;
            console.log(options);
            // const connectUrl = `ws://${host}:${port}${endpoint}`
            // 配置Mqtt地址
            let url = process.env.VUE_APP_MQTT_SERVER_URL;
            if (url == '') {
                console.log('自动获取mqtt连接地址');
                if (window.location.protocol === 'http:') {
                    url = 'ws://' + window.location.host + '/mqtt';
                } else {
                    url = 'wss://' + window.location.host + '/mqtt';
                }
            }
            try {
                this.client = mqtt.connect(url, this.connection);
            } catch (error) {
                // console.log('mqtt.connect error', error)
            }
            this.client.on('connect', () => {
                console.log('Connection succeeded!');
                this.message = '设备已连接';
                setTimeout(() => {
                    this.getBindList();
                }, 500);
            });
            this.client.on('error', (error) => {
                // console.log('Connection failed', error)
            });
            this.client.on('message', (topic, message) => {
                console.log(`接收消息 ${message} from topic ${topic}`);
                try {
                    this.receiveNews = this.receiveNews.concat(message);
                    let data = JSON.parse(message);
                    let topics = topic.split('/');
                    data.imei = topics[4];
                    if (data.deviceMac === topics[4]) {
                        //报警信息
                        let warnMessage = data.deviceName + '的设备于' + data.warnTime + '发出' + data.warnMessage + '，请您及时前往' + (data.address == undefined ? '' : data.address) + '处理，谢谢！';
                        let warnMsg = data.warnMessage;
                        this.warnNotice(warnMessage, warnMsg);
                    } else {
                        //设备组态推送
                        //处理imei
                        this.$emit('mqttAccept', data);
                    }
                } catch (error) {
                    console.log('解析数据出错', error);
                }
            });
        },
        doSubscribe() {
            //告警主题
            const { topic, qos } = {
                topic: '/IOT/WULIANYUN/SENDWARNMESSAGE',
                qos: 1,
            };
            this.client.subscribe(topic, qos, (error, res) => {
                if (error) {
                    return;
                }
                this.subscribeSuccess = true;
                console.log('主题订阅成功：' + topic);
            });
            //实时数据主题
            //指令下达主题
            this.bindList.forEach((element) => {
                let topic = '/IOT/WULIANYUN/REALDATA/' + element.deviceMac;
                let qos = 1;
                this.client.subscribe(topic, qos, (error, res) => {
                    console.log('topic', topic);
                    if (error) {
                        console.log('Subscribe to topics error', error);
                        return;
                    }
                });
            });
        },
        /**
         * @name:发布mqtt消息
         * @msg:
         * @param {*}
         * @return {*}
         */
        mqttPublish() {
            console.log('开始订阅', this.client);
            this.bindList.forEach((element) => {
                let topic = 'repub/to/' + element.deviceMac;
                console.log('开启预览', topic, element);
                let message = {
                    onLine: 1,
                };
                try {
                    this.client.publish(topic, JSON.stringify(message));
                    console.log('publish success');
                } catch (error) {
                    console.log('publish failed');
                }
            });
        },
        destroyConnection() {
            if (this.client.connected) {
                try {
                    this.client.end();
                    this.client = {
                        connected: false,
                    };
                    // console.log('Successfully disconnected!')
                } catch (error) {
                    // console.log('Disconnect failed', error.toString())
                }
            }
        },
        getLocalTime(nS) {
            return new Date(parseInt(nS)).toLocaleString('zh-cn', { hour12: false });
        },
        warnNotice(warnMessage, warnMsg) {
            let message =
                '<div style="width:200px;height:200px;background:#080A20;border:0px solid rgba(7,166,255,0.7)">' +
                '<div style="width:100%;height:40px;line-height:40px;border-bottom:2px solid rgba(7,166,255,0.7);margin-bottom:10px;">' +
                '<span style="margin-left:10px;color:#fff;font-size:16px;">' +
                '消息通知' +
                '</span>' +
                '</div>' +
                '<div>' +
                '<p style="color:#fff;font-size:12px;">' +
                '<i style="display:inline-block;width:8px;height:8px;background:red;margin:0 8px">' +
                '</i>' +
                warnMessage +
                '</p>';
            this.$notify({
                title: '',
                dangerouslyUseHTMLString: true,
                message: message,
                position: 'bottom-right',
                duration: 10000, //0标识不能自动关闭，默认4500
                showClose: true, //是否显示关闭按钮
                customClass: 'warnNotification',
            });
            console.log(warnMsg);
            this.play(warnMsg);
            setTimeout(() => {
                this.play(warnMsg);
            }, 300);
            setTimeout(() => {
                this.play(warnMsg);
            }, 300);
        },
    },
};
</script>

<style lang="scss">
.navbar {
    height: 50px;
    overflow: hidden;
    position: relative;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

    .hamburger-container {
        line-height: 46px;
        height: 100%;
        float: left;
        cursor: pointer;
        transition: background 0.3s;
        -webkit-tap-highlight-color: transparent;

        &:hover {
            background: rgba(0, 0, 0, 0.025);
        }
    }

    .breadcrumb-container {
        float: left;
    }

    .errLog-container {
        display: inline-block;
        vertical-align: top;
    }

    .right-menu {
        float: right;
        height: 100%;
        line-height: 50px;

        &:focus {
            outline: none;
        }

        .right-menu-item {
            display: inline-block;
            padding: 0 8px;
            height: 100%;
            font-size: 18px;
            color: #5a5e66;
            vertical-align: text-bottom;

            &.hover-effect {
                cursor: pointer;
                transition: background 0.3s;

                &:hover {
                    background: rgba(0, 0, 0, 0.025);
                }
            }
        }

        .avatar-container {
            margin-right: 30px;

            .avatar-wrapper {
                margin-top: 5px;
                position: relative;

                .user-avatar {
                    cursor: pointer;
                    width: 40px;
                    height: 40px;
                    border-radius: 10px;
                }

                .el-icon-caret-bottom {
                    cursor: pointer;
                    position: absolute;
                    right: -20px;
                    top: 25px;
                    font-size: 12px;
                }
            }
        }
    }

    .box {
        background-color: #f08080;
    }

    .box:hover {
        background-color: red;
        cursor: pointer;
    }
}

.warnNotification {
    right: 16px !important;
    background: #080a20 !important;
    width: 250px !important;
    height: 180px !important;
    border: 1px solid #43dcff !important;
}
</style>
